package com.heima.search.listen;

import com.heima.common.message.ArticleForEsConstants;
import com.heima.search.feign.ArticleFeign;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2021/2/22 11:15
 **/
@Component
@Slf4j
public class ArticleAddOrRemoveListener {

    @Autowired
    ArticleSearchService articleSearchService;

    @Autowired
    ArticleFeign articleFeign;
    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD)
    public void addArticle(String articleId){
        log.info("索引库添加文章监听收到消息  ==>{}",articleId);
        try {
            Map article = articleFeign.findArticle(Long.valueOf(articleId));
            if(article!= null){
                articleSearchService.saveArticle(articleId,article);
            }else {
                log.error("未搜索到文章信息  ==>{}",articleId);
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库添加文章失败  ==>{}",e.getCause());
        }
    }
    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE)
    public void deleteArticle(String articleId){
        log.info("索引库删除文章监听收到消息  ==>{}",articleId);
        try {
            articleSearchService.deleteArticle(articleId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库删除文章失败  ==>{}",e.getCause());
        }
    }


}
